package com.dis.service.service.impl;

import com.dis.pojo.dto.InsureDTO;
import com.dis.pojo.entity.Insure;
import com.dis.pojo.entity.Region;
import com.dis.service.mapper.InsureMapper;
import com.dis.service.mapper.RegionMapper;
import com.dis.pojo.queryDTO.InsurePageQueryDTO;
import com.dis.common.result.PageResult;
import com.dis.service.service.InsureService;
import com.dis.pojo.vo.InsureVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InsureServiceImpl implements InsureService {

    @Autowired
    private InsureMapper insureMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public void save(InsureDTO insureDTO) {
        Insure insure = new Insure();
        BeanUtils.copyProperties(insureDTO, insure);
        insureMapper.insert(insure);
    }

    @Override
    public PageResult pageQuery(InsurePageQueryDTO insurePageQueryDTO) {
        // 1. 使用 PageHelper 开始分页
        PageHelper.startPage(insurePageQueryDTO.getPage(), insurePageQueryDTO.getPageSize());

        // 2. 查询当前页数据（PageHelper 会自动添加 LIMIT）
        List<Insure> insureList = insureMapper.pageQuery(insurePageQueryDTO);

        // 3. 获取 Page 对象（包含分页信息）
        Page<Insure> page = (Page<Insure>) insureList;

        // 4. 查询所有相关的地区信息
        List<Integer> regionIds = insureList.stream()
                .flatMap(insure -> Arrays.asList(
                        insure.getCountryId(),
                        insure.getProvinceId(),
                        insure.getCityId(),
                        insure.getDistrictId(),
                        insure.getTownId()
                ).stream())
                .filter(regionId -> regionId != null)
                .distinct()
                .collect(Collectors.toList());

        Map<Integer, String> regionMap = CollectionUtils.isEmpty(regionIds) ?
                Collections.emptyMap() :
                regionMapper.selectByIds(regionIds).stream()
                        .collect(Collectors.toMap(Region::getRegionId, Region::getRegionName));

        // 5. 转换为 VO 对象
        List<InsureVO> insureVOList = insureList.stream().map(insure -> {
            InsureVO insureVO = new InsureVO();
            BeanUtils.copyProperties(insure, insureVO);

            // 设置地区名称
            insureVO.setCountryName(regionMap.get(insure.getCountryId()));
            insureVO.setProvinceName(regionMap.get(insure.getProvinceId()));
            insureVO.setCityName(regionMap.get(insure.getCityId()));
            insureVO.setDistrictName(regionMap.get(insure.getDistrictId()));
            insureVO.setTownName(regionMap.get(insure.getTownId()));

            return insureVO;
        }).collect(Collectors.toList());

        // 6. 返回分页结果（PageHelper 已提供总数）
        return new PageResult(page.getTotal(), insureVOList);
    }

    @Override
    public InsureVO getById(Long id) {
        Insure insure = insureMapper.getById(id);
        if (insure == null) {
            return null;
        }

        InsureVO insureVO = new InsureVO();
        BeanUtils.copyProperties(insure, insureVO);

        // 查询地区名称 - 使用Arrays.asList代替List.of
        List<Integer> regionIds = Arrays.asList(
                        insure.getCountryId(),
                        insure.getProvinceId(),
                        insure.getCityId(),
                        insure.getDistrictId(),
                        insure.getTownId()
                ).stream()
                .filter(regionId -> regionId != null) // 重命名避免冲突
                .collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(regionIds)) {
            Map<Integer, String> regionMap = regionMapper.selectByIds(regionIds).stream()
                    .collect(Collectors.toMap(Region::getRegionId, Region::getRegionName));

            insureVO.setCountryName(regionMap.get(insure.getCountryId()));
            insureVO.setProvinceName(regionMap.get(insure.getProvinceId()));
            insureVO.setCityName(regionMap.get(insure.getCityId()));
            insureVO.setDistrictName(regionMap.get(insure.getDistrictId()));
            insureVO.setTownName(regionMap.get(insure.getTownId()));
        }

        return insureVO;
    }

    @Override
    public void update(InsureDTO insureDTO) {
        Insure insure = new Insure();
        BeanUtils.copyProperties(insureDTO, insure);
        insureMapper.update(insure);
    }

    @Override
    public void delete(Long id) {
        insureMapper.delete(id);
    }
}